package cn.itcast.web.controller.system;

import cn.hutool.core.util.StrUtil;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import cn.itcast.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.Struct;
import java.util.List;

@Controller
@RequestMapping(value = "/system/dept", name = "部门管理")
public class DeptController extends BaseController {



    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list", name = "查询部门")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {

        PageInfo page = deptService.findByPage(pageNum, pageSize, getCompanyId());
        request.setAttribute("page", page);
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd", name = "新增页面")
    public String toAdd() {
        // 查询所有部门
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList", deptList);

        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/edit", name = "新增/修改")
    public String edit(Dept dept) {
        // 如果前端提交的parent.id为空串，我们需要手动设置为null
        if (StrUtil.hasEmpty(dept.getParent().getId())) {
            dept.getParent().setId(null);
        }

        // 根据id判断
        if (StrUtil.hasEmpty(dept.getId())) {
            // 关联企业id和企业名称
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            deptService.save(dept); // 新增
        } else {
            deptService.update(dept);// 修改
        }

        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "/toUpdate", name = "修改页面")
    public String toUpdate(String id) {
        // 查询所有部门
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList", deptList);
        // 查询当前部门
        Dept dept = deptService.findById(id);
        request.setAttribute("dept", dept);
        return "system/dept/dept-update";
    }


    @RequestMapping(value = "/delete",name = "删除")
    public String delete(String id){
        deptService.delete(id);

        return "redirect:/system/dept/list.do";
    }
}
